using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Comteck.Winforms.Utils {
  /// <summary>
  /// 动态json类
  /// </summary>
  public class JsonConfigHelper {
    /// <summary>
    /// 根据List生成Json
    /// </summary>
    /// <param name="configTemplet"></param>
    /// <param name="list"></param>
    /// <returns></returns>
    public static string GenerateConfig(List<(string, string, string, string)> configTemplet, List<NameValueEntity> list) {
      if (list == null) {
        return string.Empty;
      }

      using (var textWriter = new StringWriter()) {

        using (var jsonWriter = new JsonTextWriter(textWriter)) {
          jsonWriter.WriteStartObject();
          foreach (var tuple in configTemplet) {
            jsonWriter.WritePropertyName(tuple.Item1.TrimSafe());
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("value");
            jsonWriter.WriteValue(list.FirstOrDefault(x => x.Name.Equals(tuple.Item3))?.Value.TrimSafe());
            jsonWriter.WritePropertyName("desc");
            jsonWriter.WriteValue(tuple.Item3.TrimSafe());
            jsonWriter.WritePropertyName("ext");
            jsonWriter.WriteValue(tuple.Item4.TrimSafe());
            jsonWriter.WriteEndObject();
          }
          jsonWriter.WriteEndObject();
          jsonWriter.Flush();
          return textWriter.ToString();
        }
      }
    }

    /// <summary>
    /// 根据元组集合生成动态对象
    /// </summary>
    /// <param name="configTuples"></param>
    /// <returns></returns>
    public static dynamic GenerateConfig(List<(string, string, string, string)> configTuples) {
      using (var textWriter = new StringWriter()) {

        using (var jsonWriter = new JsonTextWriter(textWriter)) {
          jsonWriter.WriteStartObject();
          foreach (var tuple in configTuples) {
            jsonWriter.WritePropertyName(tuple.Item1.TrimSafe());
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("value");
            jsonWriter.WriteValue(tuple.Item2.TrimSafe());
            jsonWriter.WritePropertyName("desc");
            jsonWriter.WriteValue(tuple.Item3.TrimSafe());
            jsonWriter.WritePropertyName("ext");
            jsonWriter.WriteValue(tuple.Item4.TrimSafe());
            jsonWriter.WriteEndObject();
          }
          jsonWriter.WriteEndObject();
          jsonWriter.Flush();
          return JsonConvert.DeserializeObject(textWriter.ToString());
        }
      }
    }

  }

}
